package com.baoming.tool;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Hashtable;
  
import org.apache.struts2.ServletActionContext;

import com.baoming.code.MatrixToImageWriter;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

/**
 * 二维码生成器
 * @author Administrator
 *
 */
public class MatrixTool {
	
	public static String create(String url , String uuid){
		return craete(500 , 500 , url , uuid);
	}
	
	public static String create(String url){
		return craete(500 , 500 , url , null);
	}

	public static String craete(int width , int height , String url , String uuid){
		String path = null ; 
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		try {
			//二维码的图片格式  
			String format = "gif";  
			Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();  
			//内容所使用编码  
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");  
			BitMatrix bitMatrix = new MultiFormatWriter().encode(url,  
			BarcodeFormat.QR_CODE, width, height, hints);  
			String realPath = "code/"+formatter.format(new java.util.Date()) ; 
			String abcPath = ServletActionContext.getServletContext().getRealPath(realPath) ; 
			 
			File file = new File(abcPath) ; 
			if(!file.exists()){
				file.mkdir() ;
			}
			 
			String fileName = "/."+format ; 
			//生成二维码  
			File outputFile = new File(abcPath+fileName);   
			
			MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
			path = realPath + fileName ; 
			 
		} catch (WriterException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
		 
		return path ; 
	}
	
}
